/*
 *  HID driver for multitouch panels
 *
 *  Copyright (c) 2010-2011 Stephane Chatty <chatty@enac.fr>
 *  Copyright (c) 2010-2011 Benjamin Tissoires <benjamin.tissoires@gmail.com>
 *  Copyright (c) 2010-2011 Ecole Nationale de l'Aviation Civile, France
 *
 *  This code is partly based on hid-egalax.c:
 *
 *  Copyright (c) 2010 Stephane Chatty <chatty@enac.fr>
 *  Copyright (c) 2010 Henrik Rydberg <rydberg@euromail.se>
 *  Copyright (c) 2010 Canonical, Ltd.
 *
 *  This code is partly based on hid-3m-pct.c:
 *
 *  Copyright (c) 2009-2010 Stephane Chatty <chatty@enac.fr>
 *  Copyright (c) 2010      Henrik Rydberg <rydberg@euromail.se>
 *  Copyright (c) 2010      Canonical, Ltd.
 *
 */

/*
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 */

#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/input/mt.h>
#include "usbhid/usbhid.h"


MODULE_AUTHOR("Joonho Lee <jhlee74@gmail.com>");
MODULE_DESCRIPTION("B&S Media Optical Touch Sensor");
MODULE_LICENSE("GPL");

#define USB_VENDOR_ID_BNSMEDIA			0xFFFF
#define USB_DEVICE_ID_BNSMEDIA_BST100	0x1200
#define _dbg(x...)  printk(KERN_INFO x)


struct bsmt_slot {
	__s32 x, y, w, h;
	__s32 contactid;		/* the device ContactID assigned to this slot */
	bool touch_state;		/* is the touch valid? */
	bool seen_in_this_frame;/* has this slot been updated */
};

struct bsmt_device {
	struct bsmt_slot curdata;	/* placeholder of incoming data */
	unsigned last_field_index;	/* last field index of the report */
	unsigned last_slot_field;	/* the last field of a slot */
	int last_bsmt_collection;	/* last known mt-related collection */
	__s8 inputmode;				/* InputMode HID feature, -1 if non-existent */
	__u8 num_received;			/* how many contacts we received */
	__u8 num_expected;			/* expected last contact index */
	__u8 maxcontacts;
	struct bsmt_slot *slots;
};

#define MT_DEFAULT_MAXCONTACT	4

static int find_slot_from_contactid(struct bsmt_device *td)
{
	int i;

	for (i = 0; i < td->maxcontacts; ++i) {
		if (td->slots[i].contactid == td->curdata.contactid &&
			td->slots[i].touch_state)
			return i;
	}
	for (i = 0; i < td->maxcontacts; ++i) {
		if (!td->slots[i].seen_in_this_frame &&
			!td->slots[i].touch_state)
			return i;
	}

	/* should not occurs. If this happens that means
	 * that the device sent more touches that it says
	 * in the report descriptor. It is ignored then.
	 */
	return -1;
}

static void bsmt_feature_mapping(struct hid_device *hdev, struct hid_field *field,
	struct hid_usage *usage)
{
	struct bsmt_device *td = hid_get_drvdata(hdev);

	switch (usage->hid) {
	case HID_DG_CONTACTMAX:
		td->maxcontacts = field->value[0];
		break;
	case HID_DG_INPUTMODE:
		td->inputmode = field->report->id;
		break;
	case HID_DG_DEVICEINDEX:
		break;
	}
}

static int bsmt_input_mapping(struct hid_device *hdev, struct hid_input *hi,
	struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max)
{
	struct bsmt_device *td = hid_get_drvdata(hdev);

	/* Only map fields from TouchScreen or TouchPad collections.
	 * We need to ignore fields that belong to other collections
	 * such as Mouse that might have the same GenericDesktop usages.
	 */
	if (field->application == HID_DG_TOUCHSCREEN)
		set_bit(INPUT_PROP_DIRECT, hi->input->propbit);
	else if (field->application == HID_DG_TOUCHPAD)
		set_bit(INPUT_PROP_POINTER, hi->input->propbit);
	else {
		if (field->application == HID_GD_MOUSE) {
			//_dbg("===> HID_GD_MOUSE : 0x%x\n", usage->hid);
		} else if (field->application == HID_GD_KEYBOARD) {
			//_dbg("===> HID_GD_KEYBOARD : 0x%x\n", usage->hid);
		}
		return 0;
	}

	switch (usage->hid & HID_USAGE_PAGE) {
	case HID_UP_GENDESK:
		switch (usage->hid) {
		case HID_GD_X:
			hid_map_usage(hi, usage, bit, max, EV_ABS, ABS_MT_POSITION_X);
			input_set_abs_params(hi->input, ABS_MT_POSITION_X, field->logical_minimum, field->logical_maximum, 0, 0);
			/* touchscreen emulation */
			input_set_abs_params(hi->input, ABS_X, field->logical_minimum, field->logical_maximum, 0, 0);
			if (td->last_bsmt_collection == usage->collection_index) {
				td->last_slot_field = usage->hid;
				td->last_field_index = field->index;
			}
			return 1;
		case HID_GD_Y:
			hid_map_usage(hi, usage, bit, max, EV_ABS, ABS_MT_POSITION_Y);
			input_set_abs_params(hi->input, ABS_MT_POSITION_Y, field->logical_minimum, field->logical_maximum, 0, 0);
			/* touchscreen emulation */
			input_set_abs_params(hi->input, ABS_Y, field->logical_minimum, field->logical_maximum, 0, 0);
			if (td->last_bsmt_collection == usage->collection_index) {
				td->last_slot_field = usage->hid;
				td->last_field_index = field->index;
			}
			return 1;
		}
		return 0;

	case HID_UP_DIGITIZER:
		switch (usage->hid) {
		case HID_DG_INRANGE:
			if (td->last_bsmt_collection == usage->collection_index) {
				td->last_slot_field = usage->hid;
				td->last_field_index = field->index;
			}
			return 1;
		case HID_DG_CONFIDENCE:
			if (td->last_bsmt_collection == usage->collection_index) {
				td->last_slot_field = usage->hid;
				td->last_field_index = field->index;
			}
			return 1;
		case HID_DG_TIPSWITCH:
			hid_map_usage(hi, usage, bit, max, EV_KEY, BTN_TOUCH);
			input_set_capability(hi->input, EV_KEY, BTN_TOUCH);
			if (td->last_bsmt_collection == usage->collection_index) {
				td->last_slot_field = usage->hid;
				td->last_field_index = field->index;
			}
			return 1;
		case HID_DG_CONTACTID:
			if (!td->maxcontacts)
				td->maxcontacts = MT_DEFAULT_MAXCONTACT;
			input_mt_init_slots(hi->input, td->maxcontacts);
			td->last_slot_field = usage->hid;
			td->last_field_index = field->index;
			td->last_bsmt_collection = usage->collection_index;
			return 1;
		case HID_DG_WIDTH:
			if (td->last_bsmt_collection == usage->collection_index) {
				td->last_slot_field = usage->hid;
				td->last_field_index = field->index;
			}
			return 1;
		case HID_DG_HEIGHT:
			if (td->last_bsmt_collection == usage->collection_index) {
				td->last_slot_field = usage->hid;
				td->last_field_index = field->index;
			}
			return 1;
		case HID_DG_TIPPRESSURE:
			if (td->last_bsmt_collection == usage->collection_index) {
				td->last_slot_field = usage->hid;
				td->last_field_index = field->index;
			}
			return 1;
		case HID_DG_CONTACTCOUNT:
			if (td->last_bsmt_collection == usage->collection_index)
				td->last_field_index = field->index;
			return 1;
		case HID_DG_CONTACTMAX:
			/* we don't set td->last_slot_field as contactcount and
			 * contact max are global to the report
			 */
			if (td->last_bsmt_collection == usage->collection_index)
				td->last_field_index = field->index;
			return -1;
		}
		/* let hid-input decide for the others */
		return 0;

	case HID_UP_MSVENDOR://0xff000000:
		_dbg("===> HID_UP_MSVENDOR : 0xff000000\n");
		/* we do not want to map these: no input-oriented meaning */
		return -1;
	default:
		_dbg("===> HID_UP_??? : 0x%x\n", (usage->hid & HID_USAGE_PAGE));
		break;
	}

	return 0;
}

static int bsmt_input_mapped(struct hid_device *hdev, struct hid_input *hi,
	struct hid_field *field, struct hid_usage *usage, unsigned long **bit, int *max)
{
	if (usage->type == EV_KEY || usage->type == EV_ABS)
		set_bit(usage->type, hi->input->evbit);

	return -1;
}

/*
 * this function is called when a whole contact has been processed,
 * so that it can assign it to a slot and store the data there
 */
static void bsmt_complete_slot(struct bsmt_device *td)
{
	int slotnum = find_slot_from_contactid(td);
	td->curdata.seen_in_this_frame = true;
	if (slotnum >= 0 && slotnum < td->maxcontacts)
		td->slots[slotnum] = td->curdata;
	td->num_received++;
}

/*
 * this function is called when a whole packet has been received and processed,
 * so that it can decide what to send to the input layer.
 */
static void bsmt_emit_event(struct bsmt_device *td, struct input_dev *input)
{
	int i;

	for (i = 0; i < td->maxcontacts; ++i) {
		struct bsmt_slot *s = &(td->slots[i]);
		if (!s->seen_in_this_frame) {
			s->touch_state = false;
		}

		input_mt_slot(input, i);
		input_mt_report_slot_state(input, MT_TOOL_FINGER, s->touch_state);
		if (s->touch_state) {
#if 1
			input_event(input, EV_ABS, ABS_MT_POSITION_X, s->x);
			input_event(input, EV_ABS, ABS_MT_POSITION_Y, s->y);
#else
			/* this finger is on the screen */
			int wide = (s->w > s->h);
			/* divided by two to match visual scale of touch */
			int major = max(s->w, s->h) >> 1;
			int minor = min(s->w, s->h) >> 1;

			input_event(input, EV_ABS, ABS_MT_POSITION_X, s->x);
			input_event(input, EV_ABS, ABS_MT_POSITION_Y, s->y);
			input_event(input, EV_ABS, ABS_MT_ORIENTATION, wide);
			input_event(input, EV_ABS, ABS_MT_TOUCH_MAJOR, major);
			input_event(input, EV_ABS, ABS_MT_TOUCH_MINOR, minor);
#endif
			//_dbg("===> bsmt_emit_event(%d %d %d)\n", i, s->x, s->y);
		}
		s->seen_in_this_frame = false;
	}

	input_mt_report_pointer_emulation(input, true);
	input_sync(input);
	td->num_received = 0;
}

static int bsmt_event(struct hid_device *hid, struct hid_field *field,
	struct hid_usage *usage, __s32 value)
{
	struct bsmt_device *td = hid_get_drvdata(hid);

	if (hid->claimed & HID_CLAIMED_INPUT && td->slots) {
		switch (usage->hid) {
		case HID_DG_INRANGE:
			//_dbg("e==> HID_DG_INRANGE(%d)\n", value);
			break;
		case HID_DG_TIPSWITCH:
			td->curdata.touch_state = value;
			//_dbg("e==> HID_DG_TIPSWITCH(%d)\n", value);
			break;
		case HID_DG_CONFIDENCE:
			break;
		case HID_DG_CONTACTID:
			td->curdata.contactid = value;
			//_dbg("e==> HID_DG_CONTACTID(%d)\n", value);
			break;
		case HID_DG_TIPPRESSURE:
			break;
		case HID_GD_X:
			td->curdata.x = value;
			//_dbg("e==> HID_DG_X(%d)\n", value);
			break;
		case HID_GD_Y:
			td->curdata.y = value;
			//_dbg("e==> HID_DG_Y(%d)\n", value);
			break;
		case HID_GD_WHEEL:
			break;
		case HID_DG_WIDTH:
			td->curdata.w = value;
			break;
		case HID_DG_HEIGHT:
			td->curdata.h = value;
			break;
		case HID_DG_CONTACTCOUNT:
			/*
			 * Includes multi-packet support where subsequent
			 * packets are sent with zero contactcount.
			 */
			if (value)
				td->num_expected = value;
			//_dbg("e==> HID_DG_CONTACTCOUNT(%d)\n", value);
			break;

		default:
			/* fallback to the generic hidinput handling */
			return 0;
		}

		if (usage->hid == td->last_slot_field) {
			bsmt_complete_slot(td);
		}

		if (field->index == td->last_field_index && td->num_received >= td->num_expected) {
			bsmt_emit_event(td, field->hidinput->input);
			td->num_expected = 0;
		}
	}

	/* we have handled the hidinput part, now remains hiddev */
	if (hid->claimed & HID_CLAIMED_HIDDEV && hid->hiddev_hid_event)
		hid->hiddev_hid_event(hid, field, usage, value);

	return 1;
}

static void bsmt_set_input_mode(struct hid_device *hdev)
{
	struct bsmt_device *td = hid_get_drvdata(hdev);
	struct hid_report *r;
	struct hid_report_enum *re;

	_dbg("===> td->inputmode(%d)\n", td->inputmode);
	if (td->inputmode < 0)
		return;

	re = &(hdev->report_enum[HID_FEATURE_REPORT]);
	r = re->report_id_hash[td->inputmode];
	if (r) {
		r->field[0]->value[0] = 0x02;
		usbhid_submit_report(hdev, r, USB_DIR_OUT);
		_dbg("===> usbhid_submit_report(0x02)\n");
	}
}

static int bsmt_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
	int ret;
	struct bsmt_device *td;

	if (HID_TYPE_USBMOUSE != hdev->type) {
		_dbg("===> bsmt_probe() : HID_TYPE_USBMOUSE != hdev->type\n");
		return -ENODEV;
	}

	/* This allows the driver to correctly support devices
	 * that emit events over several HID messages.
	 */
	hdev->quirks |= HID_QUIRK_NO_INPUT_SYNC;

	td = kzalloc(sizeof(struct bsmt_device), GFP_KERNEL);
	if (!td) {
		dev_err(&hdev->dev, "cannot allocate multitouch data\n");
		return -ENOMEM;
	}
	td->inputmode = -1;
	td->last_bsmt_collection = -1;
	hid_set_drvdata(hdev, td);

	ret = hid_parse(hdev);
	if (ret != 0)
		goto fail;

	ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
	if (ret)
		goto fail;

	td->slots = kzalloc(td->maxcontacts * sizeof(struct bsmt_slot),
		GFP_KERNEL);
	if (!td->slots) {
		dev_err(&hdev->dev, "cannot allocate multitouch slots\n");
		hid_hw_stop(hdev);
		ret = -ENOMEM;
		goto fail;
	}

	bsmt_set_input_mode(hdev);

	return 0;

fail:
	kfree(td);
	return ret;
}

#ifdef CONFIG_PM
static int bsmt_reset_resume(struct hid_device *hdev)
{
	bsmt_set_input_mode(hdev);
	return 0;
}
#endif

static void bsmt_remove(struct hid_device *hdev)
{
	struct bsmt_device *td = hid_get_drvdata(hdev);
	hid_hw_stop(hdev);
	kfree(td->slots);
	kfree(td);
	hid_set_drvdata(hdev, NULL);
}

static const struct hid_device_id bsmt_devices[] = {
	{ HID_USB_DEVICE(USB_VENDOR_ID_BNSMEDIA,
	USB_DEVICE_ID_BNSMEDIA_BST100) },
	{ }
};
MODULE_DEVICE_TABLE(hid, bsmt_devices);

static const struct hid_usage_id bsmt_grabbed_usages[] = {
	{ HID_ANY_ID, HID_ANY_ID, HID_ANY_ID },
	{ HID_ANY_ID - 1, HID_ANY_ID - 1, HID_ANY_ID - 1}
};

static struct hid_driver bsmt_driver = {
	.name = "bnsmedia-multitouch",
	.id_table = bsmt_devices,
	.probe = bsmt_probe,
	.remove = bsmt_remove,
	.input_mapping = bsmt_input_mapping,
	.input_mapped = bsmt_input_mapped,
	.feature_mapping = bsmt_feature_mapping,
	.usage_table = bsmt_grabbed_usages,
	.event = bsmt_event,
#ifdef CONFIG_PM
	.reset_resume = bsmt_reset_resume,
#endif
};

static int __init bsmt_init(void)
{
	return hid_register_driver(&bsmt_driver);
}

static void __exit bsmt_exit(void)
{
	hid_unregister_driver(&bsmt_driver);
}

module_init(bsmt_init);
module_exit(bsmt_exit);
